package com.familyaccount.servlet;

import com.familyaccount.model.Transaction;
import com.familyaccount.model.User;
import com.familyaccount.service.TransactionService;
import com.familyaccount.service.CategoryService;
import com.familyaccount.model.Category;
import com.familyaccount.service.UserService;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

@WebServlet("/transactions/*")
public class TransactionServlet extends HttpServlet {
    private TransactionService transactionService;
    private CategoryService categoryService;
    private UserService userService;

    @Override
    public void init() throws ServletException {
        transactionService = new TransactionService();
        categoryService = new CategoryService();
        userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        String pathInfo = request.getPathInfo();

        // 新增：处理 error 参数
        String error = request.getParameter("error");
        if (error != null && !error.isEmpty()) {
            request.setAttribute("error", error);
        }

        try {
            if (pathInfo == null || pathInfo.equals("/")) {
                // List transactions with filters
                handleListTransactions(request, response, user);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Exception e) {
            request.setAttribute("error", "获取数据时发生错误，请稍后重试。");
            request.getRequestDispatcher("/transactions.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        String pathInfo = request.getPathInfo();

        try {
            if (pathInfo == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else if (pathInfo.equals("/add")) {
                handleAddTransaction(request, response, user);
            } else if (pathInfo.equals("/edit")) {
                handleEditTransaction(request, response, user);
            } else if (pathInfo.equals("/delete")) {
                handleDeleteTransaction(request, response, user);
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Exception e) {
            request.setAttribute("error", "操作失败，请稍后重试。");
            request.getRequestDispatcher("/transactions.jsp").forward(request, response);
        }
    }

    private void handleListTransactions(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException, SQLException {
        // Get filter parameters
        String startDateStr = request.getParameter("startDate");
        String endDateStr = request.getParameter("endDate");
        String type = request.getParameter("type");
        String categoryIdStr = request.getParameter("categoryId");
        String userIdStr = request.getParameter("userId");

        // Parse dates
        LocalDate startDate = startDateStr != null && !startDateStr.isEmpty() 
                ? LocalDate.parse(startDateStr) 
                : LocalDate.now().minusMonths(1);
        LocalDate endDate = endDateStr != null && !endDateStr.isEmpty() 
                ? LocalDate.parse(endDateStr) 
                : LocalDate.now();

        // Get userId for filter
        Integer filterUserId = null;
        if (userIdStr != null && !userIdStr.isEmpty()) {
            filterUserId = Integer.parseInt(userIdStr);
        }
        // 如果userId为空，则不过滤用户

        // Get transactions
        List<Transaction> transactions;
        if (filterUserId != null) {
            transactions = transactionService.getTransactions(
                filterUserId, startDate, endDate, type, 
                categoryIdStr != null && !categoryIdStr.isEmpty() ? Integer.parseInt(categoryIdStr) : null);
        } else {
            // 查询所有用户的收支记录
            transactions = transactionService.getTransactions(
                null, startDate, endDate, type, 
                categoryIdStr != null && !categoryIdStr.isEmpty() ? Integer.parseInt(categoryIdStr) : null);
        }

        // 查询所有分类并设置到request
        List<Category> categories = categoryService.getAllCategories();
        request.setAttribute("categories", categories);

        // 查询所有用户并设置到request
        List<User> allUsers = userService.getAllUsers();
        request.setAttribute("allUsers", allUsers);
        request.setAttribute("selectedUserId", filterUserId);

        // Set attributes
        request.setAttribute("transactions", transactions);
        request.getRequestDispatcher("/transactions.jsp").forward(request, response);
    }

    private void handleAddTransaction(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException, SQLException {
        Transaction transaction = new Transaction();
        transaction.setCreatedBy(user.getId());
        transaction.setCategoryId(Integer.parseInt(request.getParameter("categoryId")));
        transaction.setAmount(new BigDecimal(request.getParameter("amount")));
        transaction.setType(Transaction.TransactionType.valueOf(request.getParameter("type")));
        transaction.setDescription(request.getParameter("description"));
        transaction.setTransactionDate(LocalDate.parse(request.getParameter("transactionDate")));

        if (transactionService.addTransaction(transaction)) {
            response.sendRedirect(request.getContextPath() + "/transactions");
        } else {
            request.setAttribute("error", "添加记录失败，请稍后重试。");
            request.getRequestDispatcher("/transactions.jsp").forward(request, response);
        }
    }

    private void handleEditTransaction(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException, SQLException {
        int transactionId = Integer.parseInt(request.getParameter("id"));
        Transaction target = transactionService.getTransactionById(transactionId);
        if (target == null) {
            setErrorAndForward(request, response, "要编辑的记录不存在。");
            return;
        }
        // 权限校验
        if (user.isGod()) {
            // GOD可操作所有记录
        } else if (user.isAdmin()) {
            // ADMIN只能操作普通用户的收支记录
            User creator = userService.getUserById(target.getCreatedBy());
            if (creator == null || creator.isGod() || creator.isAdmin()) {
                setErrorAndForward(request, response, "无权操作超级管理员或其他管理员的收支记录！");
                return;
            }
        } else {
            // USER只能操作自己
            if (target.getCreatedBy() != user.getId()) {
                setErrorAndForward(request, response, "无权操作他人的收支记录！");
                return;
            }
        }
        Transaction transaction = new Transaction();
        transaction.setId(transactionId);
        transaction.setCreatedBy(target.getCreatedBy()); // 保持原创建者
        transaction.setCategoryId(Integer.parseInt(request.getParameter("categoryId")));
        transaction.setAmount(new BigDecimal(request.getParameter("amount")));
        transaction.setType(Transaction.TransactionType.valueOf(request.getParameter("type")));
        transaction.setDescription(request.getParameter("description"));
        transaction.setTransactionDate(LocalDate.parse(request.getParameter("transactionDate")));

        boolean success;
        if (user.isGod()) {
            success = transactionService.updateTransactionByAdmin(transaction);
        } else {
            success = transactionService.updateTransaction(transaction);
        }
        if (success) {
            response.sendRedirect(request.getContextPath() + "/transactions");
        } else {
            setErrorAndForward(request, response, "更新记录失败，请稍后重试。");
        }
    }

    private void handleDeleteTransaction(HttpServletRequest request, HttpServletResponse response, User user) 
            throws ServletException, IOException, SQLException {
        int transactionId = Integer.parseInt(request.getParameter("id"));
        Transaction target = transactionService.getTransactionById(transactionId);
        if (target == null) {
            setErrorAndForward(request, response, "要删除的记录不存在。");
            return;
        }
        // 权限校验
        if (user.isGod()) {
            // GOD可操作所有记录
        } else if (user.isAdmin()) {
            // ADMIN只能操作普通用户的收支记录
            User creator = userService.getUserById(target.getCreatedBy());
            if (creator == null || creator.isGod() || creator.isAdmin()) {
                setErrorAndForward(request, response, "无权操作超级管理员或其他管理员的收支记录！");
                return;
            }
        } else {
            // USER只能操作自己
            if (target.getCreatedBy() != user.getId()) {
                setErrorAndForward(request, response, "无权操作他人的收支记录！");
                return;
            }
        }
        boolean success;
        if (user.isGod()) {
            success = transactionService.deleteTransactionByAdmin(transactionId);
        } else {
            success = transactionService.deleteTransaction(transactionId, user.getId());
        }
        if (success) {
            response.sendRedirect(request.getContextPath() + "/transactions");
        } else {
            setErrorAndForward(request, response, "删除记录失败，请稍后重试。");
        }
    }

    // 工具方法：设置错误并redirect到列表页
    private void setErrorAndForward(HttpServletRequest request, HttpServletResponse response, String errorMsg) throws IOException {
        response.sendRedirect(request.getContextPath() + "/transactions?error=" + java.net.URLEncoder.encode(errorMsg, "UTF-8"));
    }
} 